package com.github.ecbp.common.utils.excel.utils;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ExcelUitls {
    protected static final Logger logger = LoggerFactory.getLogger(ExcelUitls.class);

    /**
     * 解析, 支持多个sheet (>=1)
     *
     * @param inputStream
     * @param listeners
     * @return
     */
    public static <T> List<T> simpleRead(InputStream inputStream, List<AbstractExcelOperationListener<T>> listeners) {
        ExcelReader excelReader = null;
        try {
            excelReader = EasyExcelFactory.read(inputStream)
                    .build();

            // 可解析多个sheet
            int size = listeners.size();
            List<ReadSheet> readSheetList = new ArrayList<>(size);
            for (int i = 0; i < size; i++) {
                ReadSheet readSheet1 = EasyExcel.readSheet(i)
                        .head(listeners.get(i).getClassType())
                        .headRowNumber(listeners.get(i).getHeadNumber())
                        .registerReadListener(listeners.get(i))
                        .build();
                readSheetList.add(readSheet1);
            }
            excelReader.read(readSheetList);
        } catch (Exception e) {
            logger.error("异常", e);
        } finally {
            if (null != excelReader) {
                excelReader.finish();
            }
        }
        return null;
    }
}
